<template>
  <div id="LiveRoom" class="room">
    <!-- <div class="header">
      <div class="title">
        <h3>{{ $route.meta.subTitle }}-{{ taskTitle }}</h3>
        <span v-if="video">{{ downStatusFormat[video.downStatus].value }}</span>
      </div>
    </div> -->
    <div class="main flex-row js-between">
      <div ref="videoArea" class="center op-area">
        <div v-if="video" class="videoStatus">{{ downStatusFormat[video.downStatus].value }}</div>
        <div id="mainContainer" class="up s-border">
          <live-video-area-view
            v-if="video && video.sourceUrl"
            id="mainPlayer"
            ref="mainPlayer"
            :url="video.taskUrl?video.taskUrl:video.sourceUrl"
            style="width: 100%; height: 100%;"
            @watchState="watchState"/>
        </div>
        <div class="down  flex-row ai-center ">
          <div class="top_operation">
            <div class="buttons">
              <p>
                <span v-show="!isPlay" class="" @click="onPlay">
                  <img src="../../../assets/icon/play1.png" alt="">
                <!-- <el-button class="filter-item" @click="onPlay">
                  播放
                </el-button> -->
                </span>
                <span v-show="isPlay" class="" @click="onPause">
                  <img src="../../../assets/icon/suspend.png" alt="">
                <!-- <el-button class="filter-item" @click="onPause">
                  暂停
                </el-button> -->
                </span>
              </p>
              <p>
                <span style="margin-right:8px;" @click="onSaveStart">
                  <img v-show="vStart" src="../../../assets/icon/select_start.png" alt="">
                  <img v-show="!vStart" src="../../../assets/icon/start.png" alt="">
                <!-- <el-button class="filter-item" @click="onSaveStart">
                  <div>记录起点</div>
                </el-button> -->
                </span>
                <span @click="onSaveEnd">
                  <img v-show="vEnd" src="../../../assets/icon/select_stop.png" alt="">
                  <img v-show="!vEnd" src="../../../assets/icon/stop.png" alt="">
                <!-- <el-button class="filter-item" @click="onSaveEnd">
                  <div>记录终点</div>
                </el-button> -->
                </span>
              </p>
              <p class="quick">
                <span class="back" @click="onMove(second,false)">
                  <img src="../../../assets/icon/back.png" alt="">
                </span>
                <el-dropdown @command="handleCommand">
                  <span class="el-dropdown-link">
                    {{ second }} s
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="(item, index) in timeList"
                      :command="item.t"
                      :key="index"
                    >
                      {{ item.t }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <span class="go" @click="onMove(second,true)">
                  <img src="../../../assets/icon/go.png" alt="">
                </span>
              </p>
            </div>
            <p class="i-select">
              <span class="dowm_item">
                <el-select v-model="clipModule.confId" class="setWidth1" placeholder="选择视频模板">
                  <el-option
                    v-for="item in module_option"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </span>
            </p>
            <!-- <p v-for="(item, index) in timeList" :key="index">
              <span class="dowm_item">
                <img style="width:30px;" src="../../../assets/icon/go.png" alt="">
                <el-button class="filter-item" @click="onMove(item.f)">
                  快进{{ fot(item.f) }}s
                </el-button>
              </span>
              <span class="dowm_item">
                <img style="width:30px;" src="../../../assets/icon/back.png" alt="">
                <el-button class="filter-item" @click="onMove(item.a)">
                  快退{{ fot(item.a) }}s
                </el-button>
              </span>
            </p> -->

          </div>
          <div class="inputs">
            <p>
              <span class="dowm_item">
                <el-input v-model="clipModule.title" type="textarea" resize="none" placeholder="填写素材名称"/>
              </span>
            </p>
            <!-- <p class="i-select">
              <span class="dowm_item">
                <el-select v-model="clipModule.confId" class="setWidth" placeholder="选择视频模板">
                  <el-option
                    v-for="item in module_option"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </span>
            </p> -->
            <p>
              <span class="dowm_item">
                <el-button class="filter-item" type="success" style="width:100%;margin-top:10px;" @click="onSaveOneClip(true)">
                  合条剪辑
                </el-button>
              </span>
            </p>
          </div>
          <div class="timeInfo">
            <p v-show="vtimes.length==0" class="noData">暂无起止时间点记录~</p>
            <draggable v-model="vtimes" :options="dragOptions" element="p" @update="onDrag">
              <p v-for="(item, index) in vtimes" :key="index" class="timeitem">
                <span>
                  <span style="margin-right:20px;" class="">开始时间：{{ formatTime(item.s) }}</span>
                  <span class="">结束时间：{{ formatTime(item.e) }}</span>
                </span>
                <span class="operation">
                  <el-tooltip content="单条剪辑" placement="top">
                    <el-button size="mini" type="success" icon="el-icon-scissors" circle @click="onSaveOneClip(false,item)"/>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="delTimes(index)"/>
                  </el-tooltip>
                  <el-tooltip content="拖动排序" placement="top">
                    <el-button class="sort" size="mini" type="warning" icon="el-icon-sort" circle/>
                  </el-tooltip>
                </span>
              </p>
            </draggable>
          </div>
        </div>
      </div>
      <div v-loading.lock="LoadingData" :style="{height:computedHeight}" class="right flex-col js-start" style="position: relative;">
        <!-- <el-tabs v-model="tabs" type="card" style="margin:0 8px;">
          <el-tab-pane label="剪辑" name="1"/>
          <el-tab-pane label="文本" name="2"/>
          <el-tab-pane label="话术" name="3"/>
        </el-tabs> -->
        <div v-show="clipForm.length === 0" class="empity">空空如也，快去剪辑吧</div>
        <div style="padding-bottom:10px;margin:0 8px;">
          <el-button class="filter-item" style="background:#F56C6C;color:#fff;" @click="saveAll">
            批量剪辑
          </el-button>
          <!-- <el-button class="filter-item" style="background:#F56C6C;color:#fff;" @click="onExit">
            保存状态并退出
          </el-button> -->
          <span style="font-weight:bold;">素材数 {{ clipForm.length }}</span>
        </div>
        <div class="clipListInfo">
          <div v-for="(item, index) in clipForm" :key="index" class="oneclipinfo">
            <el-form ref="form" :inline="false" label-position="top" label-width="80px">
              <el-form :inline="true" label-position="top">
                <el-form-item label="视频名称">
                  <el-input :disabled="item.readOnly" v-model="item.title" class="setWidth" type="textarea" style="" resize="none" />
                </el-form-item>
                <el-form-item label="关键字">
                  <el-input :disabled="item.readOnly" v-model="item.keywords" class="setWidth" type="textarea" style="" resize="none" placeholder="多个关键字用逗号隔开"/>
                </el-form-item>
              </el-form>
              <el-form :inline="true" label-position="top">
                <el-form-item label="展示模板">
                  <el-select :disabled="item.readOnly" v-model="item.confId" class="select setWidth" placeholder="请选择">
                    <el-option
                      v-for="item in module_option"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="选择地区">
                  <el-cascader
                    :disabled="item.readOnly"
                    v-model="item.loc"
                    :options="cityList"
                    :props="{
                      expandTrigger: 'hover',
                      value:'id',
                      label:'name'
                    }"
                    class="setWidth"
                  />
                </el-form-item>
              </el-form>
              <el-form-item label="标签">
                <el-cascader
                  :disabled="item.readOnly"
                  v-model="item.cateList"
                  :options="cateOptions"
                  :props="{
                    expandTrigger: 'hover',
                    value:'id',
                    label:'name',
                    multiple: true
                  }"
                  class="setWidth"
                />
              </el-form-item>
              <el-form-item label="起止时间" class="timeInfo">
                <div class="info">
                  <!-- 单条剪辑的时间显示 -->
                  <div v-if="!item.multi">
                    <el-input :disabled="item.readOnly" v-model="item.startTime" style="width:100px;" resize="none" placeholder="开始时间" @blur="changeStr(item,item.multi)"/>
                    -
                    <el-input :disabled="item.readOnly" v-model="item.endTime" style="width:100px;" resize="none" placeholder="结束时间" @blur="changeend(item,item.multi)"/>
                    <span>视频时长 {{ item['length'] }} s</span>
                  </div>
                  <!-- 合条剪辑的时间显示 -->
                  <div v-else>
                    <p v-for="(t, index) in item.parts" :key="index" class="time">
                      <el-input :disabled="item.readOnly" v-model="t.start" style="width:100px;" resize="none" placeholder="开始时间" @blur="changeStr(t,item.multi)"/>
                      -
                      <el-input :disabled="item.readOnly" v-model="t.end" style="width:100px;" resize="none" placeholder="结束时间" @blur="changeend(t,item.multi)"/>
                      <span>视频时长 {{ t['length'] }} s</span>
                    </p>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="图片" class="upload">
                <img-upload
                  :disabled="item.readOnly"
                  :file-list="item.picList"
                  @onSuccess="(fileList)=>{uploadCallback(fileList,item)}"
                  @onRemove="(fileList)=>{uploadCallback(fileList,item)}"
                />
              </el-form-item>
              <el-form-item>
                <el-button class="filter-item" @click="updateInfo(item,index)">{{ item.readOnly?'修改':'保存' }}信息</el-button>
                <el-button class="filter-item" @click="submitClip(item,index)">剪辑并发布</el-button>
                <el-button class="filter-item" @click="delclip(item,index)">删除</el-button>
                <span style="color:#F56C6C;margin-left:10px;">{{ clipStatusFormat[item.status].value }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 文本 -->
        <div v-show="tabs==2" class="text">
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in textTranslation.text"
              :key="index"
              :timestamp="`${formatTime(item.b/1000)} - ${formatTime(item.e/1000)}`"
              type="warning"
              placement="top"
              style="cursor:pointer;"
              @click.native="jumpVideoPosition(item.b)">
              {{ item.text }}
            </el-timeline-item>
          </el-timeline>
        </div>
        <!-- 话术 -->
        <div v-show="tabs==3" class="speech">
          <!-- <el-collapse v-model="activeName" accordion>
            <el-collapse-item v-for="(item, index) in textTranslation.speech" :name="index" :key="index" title="一致性 Consistency">
              <el-timeline>
                <el-timeline-item
                  v-for="(s, index) in item.c"
                  :key="index"
                  :color="item.f==1?'#F56C6C':''"
                  :timestamp="`${formatTime(s.b/1000)} - ${formatTime(s.e/1000)}`"
                  placement="top"
                  style="cursor:pointer;"
                  type="info"
                >
                  {{ s.text }}
                </el-timeline-item>
              </el-timeline>
            </el-collapse-item>
          </el-collapse> -->
          <el-timeline>
            <div
              v-for="(item, index) in textTranslation.speech"
              :key="index"
              :class="item.f==1?'speechitem':''">
              <el-timeline-item
                v-for="(s, index) in item.c"
                :key="index"
                :color="item.f==1?'#F56C6C':''"
                :timestamp="`${formatTime(s.b/1000)} - ${formatTime(s.e/1000)}`"
                placement="top"
                style="cursor:pointer;"
                type="info"
              >
                {{ s.text }}
              </el-timeline-item>
            </div>
          </el-timeline>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiVideo } from '../../../api/clip/task'
import LocalVideoAreaView from './views/LocalVideoAreaView'
import DivButton from '../../../components/common/DivButton'
import FileUploader from '../../../components/common/FileUploader'
import ObjectUtil from '../../../utils/object-util'
import Fn from '../../../utils/fn'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiUpload } from '../../../api/upload'
import { apiCommon } from '../../../api/common'
import TimeUtil from '../../../utils/time-util'
import { getToken } from '../../../utils/auth'
import LiveVideoAreaView from './views/LiveVideoAreaView'
import imgUpload from '../../../components/common/imgUpload'
import {
  ClipListSourceTypeContants,
  MeterialClipTypeContants,
  downStatusFormat,
  clipStatusFormat,
  lenTypeFormat
} from '../../../mixin/MixinContants'
import draggable from 'vuedraggable'
import elementResizeDetectorMaker from 'element-resize-detector'
export default {
  name: 'RadioMeterialClipEdit',
  components: {
    LiveVideoAreaView,
    LocalVideoAreaView,
    DivButton,
    FileUploader,
    draggable,
    imgUpload
  },
  mixins: [
    ClipListSourceTypeContants.mixin,
    MeterialClipTypeContants.mixin,
    downStatusFormat.mixin,
    clipStatusFormat.mixin,
    lenTypeFormat.mixin
  ],
  data() {
    return {
      second: 0.1,
      isPlay: false,
      uploadUrl: apiUpload.upload_url,
      header: { 'Authorization': 'Bearer ' + getToken() },
      // 文本翻译
      textTranslation: {
        text: [], // 文本
        speech: []// 话术
      },
      tabs: '1',
      // 右侧列表的高
      computedHeight: 0,
      dragOptions: {
        handle: '.sort',
        animation: 500
      },
      vtimes: [],
      timeList: [
        { t: 0.1 },
        { t: 0.2 },
        { t: 0.5 },
        { t: 1 },
        { t: 2 }
      ],
      LoadingData: true,
      // 默认关键字
      defaultKeywords: '',
      cityList: [],
      // 素材任务id
      taskId: undefined,
      video: undefined,
      vStart: undefined, // 开始时间
      vEnd: undefined, // 结束时间
      // 生成剪辑的params
      clipModule: {
        title: '',
        confId: '',
        posterUrl: '',
        clipType: 1
      },
      // 右侧片段列表
      clipForm: [],
      // 模板选项
      module_option: [],
      cateOptions: [], // 分类列表
      taskTitle: '',
      // 监听对象
      elemListen: null
    }
  },
  created() {
    this.taskId = this.$route.query.id
    this.taskTitle = this.$route.query.title || ''
    this.Init()
  },
  mounted() {
    this.elemListen = elementResizeDetectorMaker()
    this.elemListen.listenTo(document.querySelector('.op-area'), element => {
      this.$nextTick(() => {
        this.computedHeight = `${element.clientHeight}px`
      })
    })
  },
  destroyed() {
    this.elemListen.removeAllListeners(document.querySelector('.op-area'))
  },
  methods: {
    handleCommand(val) {
      this.second = val
    },
    // 获取视频播放状态
    watchState(player) {
      this.isPlay = player.playing
    },
    /**
     * @name: 快进快退时间格式化
     * @param {*} val 时间参数
     * @return {*}
     */
    fot(val) {
      if (val > 0) {
        return val
      } else {
        return String(val).split('-')[1]
      }
    },
    // 时间格式化工具方法
    formatTime(val) {
      return TimeUtil.secondsToTime(val)
    },
    // 图片上传回调
    uploadCallback(fileList, item) {
      const success = fileList.every(item => item.status === 'success')
      if (success) item.picList = fileList.map(item => ({ url: item.response ? item.response.datas.url : item.url }))
    },
    beforePosterUpload() {

    },
    // 跳转播放
    jumpVideoPosition(time) {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.currentTime(TimeUtil.millisecondtoSecond(time))
      }
    },
    delTimes(index) {
      this.vtimes.splice(index, 1)
    },
    // 拖拽排序触发
    onDrag(val) {
      console.log(val, '重排后的数组')
    },
    // tree结构格式化，去二级children
    formatList(list) {
      list.forEach(item => {
        item.children.forEach(c => {
          c.children = undefined
        })
      })
      return list
    },
    // 省市信息
    getAreaList() {
      return new Promise((resolve, reject) => {
        apiCommon.arealist().then(res => {
          if (res.data.resp_code == 0) {
            this.cityList = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 获取关联的分类信息
    relationCategory() {
      return new Promise((resolve, reject) => {
        apiMeterial.relationCategory().then(res => {
          if (res.data.resp_code == 0) {
            this.cateOptions = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res.data)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 开始时间修改
    changeStr(item, multi) {
      const end = TimeUtil.TimeToseconds(multi ? item.end : item.endTime)
      const start = TimeUtil.TimeToseconds(multi ? item.start : item.startTime)
      if (start > end) {
        return this.toast.fail('结束时间不能小于开始时间')
      }
      item['length'] = (end - start)
    },
    // 结束时间修改
    changeend(item, multi) {
      const end = TimeUtil.TimeToseconds(multi ? item.end : item.endTime)
      const start = TimeUtil.TimeToseconds(multi ? item.start : item.startTime)
      if (start > end) {
        return this.toast.fail('结束时间不能小于开始时间')
      }
      item['length'] = (end - start)
    },
    /**
     * 格式化分类数据
     * @argument type 1[[...],[...]] to 一级:[],二级:[]  2一级:[],二级:[] to [[...],[...]]
    */
    formatCate(type, cateList) {
      let cateInfo = null
      let filterData = null
      if (type == 1) {
        filterData = [...new Set([].concat(...cateList))]
        cateInfo = { cateOneList: [], cateTwoList: [] }
        filterData.forEach(item => {
          this.cateOptions.forEach(cate => {
            if (item == cate.id) {
              cateInfo.cateOneList.push({ ...cate })
            } else {
              cate.children && cate.children.forEach(c => {
                if (item == c.id) {
                  cateInfo.cateTwoList.push({ ...c })
                }
              })
            }
          })
        })
      } else {
        cateInfo = []
        cateList && cateList.forEach(item => {
          item.children.forEach(c => {
            cateInfo.push([item.id, c.id])
          })
        })
      }
      return cateInfo
    },
    // 地区格式化
    formatLoc(loc) {
      let cityInfo = []
      this.cityList && this.cityList.forEach(p => {
        p.children && p.children.forEach(c => {
          if (c.id == loc) {
            cityInfo = [p.id, c.id]
          }
        })
      })
      return cityInfo
    },
    // 获取素材下的所有剪辑
    async getcliplist() {
      const form = {
        taskId: this.taskId,
        clipType: 1
      }
      const [err, res] = await this.$await(apiVideo.cliplist_all(form))
      if (!err) {
        const result = res.datas.list || []
        this.LoadingData = false
        this.clipForm = result.map(item => {
          // 处理合条的时间
          let parts = item.multi ? JSON.parse(item.parts) : []
          parts = ObjectUtil.notEmpty(parts) ? parts.map(t => {
            return {
              ...t,
              start: TimeUtil.secondsToTime(t.start),
              end: TimeUtil.secondsToTime(t.end)
            }
          }) : undefined
          // 处理图片
          let picList = (item.picList && ObjectUtil.confirmArray(JSON.parse(item.picList))) || []
          picList = picList.map(item => ({ url: item }))
          return {
            ...item,
            parts,
            endTime: item.endTime ? TimeUtil.secondsToTime(item.endTime) : undefined,
            startTime: item.startTime ? TimeUtil.secondsToTime(item.startTime) : undefined,
            prov: item.prov || '',
            readOnly: true,
            loc: this.formatLoc(item.loc) || [],
            cateList: this.formatCate(2, item.cateTrees),
            picList
          }
        })
      }
    },
    // 删除某个片段
    delclip: Fn.Confirm(async function(item, index) {
      const [err, res] = await this.$await(apiVideo.delClip({ id: item.id }))
      if (res) {
        this.toast.success('删除成功')
        this.getcliplist()
      }
    }),
    // 获取剪辑模板
    async getclipTempl() {
      const [err, res] = await this.$await(apiVideo.templOptions())
      if (res) {
        this.module_option = res.datas.list
      }
    },
    // 获取期数id下的分类
    async getIdCate(playId) {
      const [err, res] = await this.$await(apiMeterial.searchPeriodId({ playId }))
      if (res) {
        const result = res.datas || {}
        const { radioName, channelName, programmeName, liveHostsName } = result
        this.defaultKeywords = [radioName, channelName, programmeName, liveHostsName].join(',') || ''
      }
    },
    fixed(num) {
      return parseFloat(num.toFixed(3))
    },
    // 素材剪辑信息
    async videoDetail() {
      const [err, res] = await this.$await(apiVideo.read({ id: this.taskId }))
      if (!err) {
        this.video = res.datas
        this.taskTitle = this.video.title
        if (this.video.playId) {
          this.getIdCate(this.video.playId)
        }
        // const { beSplit, textSegment } = res.datas
        // this.textTranslation = {
        //   text: JSON.parse(textSegment),
        //   speech: JSON.parse(beSplit)
        // }
      }
    },
    // 初始化页面
    async Init() {
      this.getclipTempl()
      this.videoDetail()
      await this.getAreaList()
      await this.relationCategory()
      this.getcliplist()
    },
    // 退出
    onExit: Fn.Confirm(function() {
      this.$router.go(-1)
    }),
    // 设置封面
    onSetPoster() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.clipModule.posterUrl = this.$refs.mainPlayer.clipImage()
      }
    },
    // 记录起点
    onSaveStart() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.stop()
        this.vStart = this.$refs.mainPlayer.currentTime()
      }
      if (this.vStart >= this.vEnd) {
        this.$notify.warning({
          title: '提示',
          message: '起点不能大于终点，请重新选择'
        })
        this.vEnd = undefined
      }
    },
    // 记录终点
    onSaveEnd: Fn.Debounce(function() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.$refs.mainPlayer.stop()
        this.vEnd = this.$refs.mainPlayer.currentTime()
      }
      if (this.vStart >= this.vEnd) {
        this.$notify.warning({
          title: '提示',
          message: '起点不能大于终点，请重新选择'
        })
        this.vEnd = undefined
      } else {
        if (ObjectUtil.allNotNull(this.vStart, this.vEnd)) {
          this.vtimes.push({
            s: this.fixed(this.vStart),
            e: this.fixed(this.vEnd),
            length: this.fixed((this.vEnd - this.vStart))
          })
          // this.vStart = this.vEnd = undefined
        }
      }
    }),
    // 前进后退
    onMove(step, state) {
      if (!step) return this.toast.fail('请选择快进快退倍数')
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        if (state) {
          this.$refs.mainPlayer.currentTime(this.$refs.mainPlayer.currentTime() + step)
        } else {
          this.$refs.mainPlayer.currentTime(this.$refs.mainPlayer.currentTime() - step)
        }
      }
    },
    // 暂停
    onPause() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.vEnd = this.$refs.mainPlayer.stop()
      }
    },
    // 播放
    onPlay() {
      if (ObjectUtil.notNull(this.$refs.mainPlayer)) {
        this.vEnd = this.$refs.mainPlayer.play()
      }
    },
    // 剪辑信息非空校验
    validate() {
      const that = this
      if (!ObjectUtil.notEmpty(that.clipModule.title)) {
        that.$notify.warning({
          title: '提示',
          message: '剪辑标题不能为空'
        })
        return false
      }
      if (!that.clipModule.confId) {
        that.$notify.warning({
          title: '提示',
          message: '选择模板'
        })
        return false
      }
      if (that.vtimes.length === 0) {
        that.$notify.warning({
          title: '提示',
          message: '请设置起止时间'
        })
        return false
      }
      if (that.clipModule.endTime <= that.clipModule.startTime) {
        that.$notify.warning({
          title: '提示',
          message: '开始时间不能大于结束时间'
        })
        return false
      }
      return true
    },
    // 校验下载状态
    downStatus() {
      const { downStatus } = this.video
      if (downStatus == 1) {
        return true
      } else if (downStatus == 2) {
        this.toast.fail('任务下载失败，无法剪辑')
        return false
      } else {
        this.toast.fail('任务下载中，稍后再试')
        return false
      }
    },
    /**
     * 设置单、合条剪辑对应的起止时间参数
     * @argument clipinfo 剪辑数据
     * @argument multi 是否为单条剪辑 true 合条 false 单条
    */
    clipTimefiled(clipInfo) {
      if (clipInfo.multi) {
        const parts = clipInfo.parts.map(_time => {
          return {
            ..._time,
            start: TimeUtil.TimeToseconds(_time.start),
            end: TimeUtil.TimeToseconds(_time.end)
          }
        })
        return { parts: JSON.stringify(parts) }
      } else {
        return {
          endTime: TimeUtil.TimeToseconds(clipInfo.endTime),
          startTime: TimeUtil.TimeToseconds(clipInfo.startTime)
        }
      }
    },
    // 批量剪辑
    saveAll: Fn.Confirm(function() {
      if (!this.downStatus()) return
      const notSaves = this.clipForm
        .filter(item => item.status == -1)
        .map(item => ({ ...item, ...this.clipTimefiled(item) }))
      if (ObjectUtil.isEmpty(notSaves)) return this.toast.fail('没有可供剪辑的素材')
      const noCate = notSaves.filter(item => item.cateList.length === 0)
      const noTitle = notSaves.filter(item => item.title === '')
      if (noCate.length > 0) return this.toast.fail('有未选择标签的剪辑，请先选择标签')
      if (noTitle.length > 0) return this.toast.fail('有未填写名称的剪辑，请先填写名称')
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const promise = []
      notSaves.forEach(ns => {
        const { cateOneList, cateTwoList } = this.formatCate(1, ns.cateList)
        ns.cateOneList = cateOneList
        ns.cateTwoList = cateTwoList
        ns.prov = ns.loc[0] || ''
        ns.loc = ns.loc[1] || ''
        ns.picList = (ObjectUtil.notEmpty(ns.picList) && JSON.stringify(ns.picList.map(item => item.url))) || ''
        this.$delete(ns, 'status')
        this.$delete(ns, 'cateList')
        this.$delete(ns, 'readOnly')
        promise.push(apiVideo.createAndClip(ns))
      })
      Promise.all(promise).then(res => {
        loading.close()
        this.toast.success('保存成功')
        this.getcliplist()
      }).catch(err => {
        console.log(err)
        loading.close()
      })
    }),
    /**
     * @param {*} oneClip 剪辑数据
     * @param {*} clip 接口
     * @return {*}
     */
    async clipInterface(oneClip, clip) {
      const item = { ...oneClip, ...this.clipTimefiled(oneClip) }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const { cateOneList, cateTwoList } = this.formatCate(1, item.cateList)
      item.cateOneList = cateOneList
      item.cateTwoList = cateTwoList
      item.prov = item.loc[0] || ''
      item.loc = item.loc[1] || ''
      item.picList = (ObjectUtil.notEmpty(item.picList) && JSON.stringify(item.picList.map(item => item.url))) || ''
      this.$delete(item, 'status')
      this.$delete(item, 'readOnly')
      this.$delete(item, 'cateList')
      const [err, res] = await this.$await(clip(item))
      if (res) {
        this.$notify.success({
          title: '成功',
          message: '提交剪辑任务成功'
        })
        this.getcliplist()
      }
      loading.close()
    },
    // 正式剪辑
    submitClip(clip) {
      if (!this.downStatus()) return
      if (clip.cateList.length === 0) {
        return this.toast.fail('请选择标签')
      }
      if (clip.title === '') {
        return this.toast.fail('请填写视频名称')
      }
      this.clipInterface(clip, apiVideo.createAndClip)
    },
    // 修改素材的基本信息（分类）
    updateInfo(item) {
      if (item.readOnly) {
        item.readOnly = !item.readOnly
        return
      } else {
        if (item.cateList.length === 0) {
          return this.toast.fail('请选择标签')
        }
        if (item.title === '') {
          return this.toast.fail('请填写视频名称')
        }
        // if (item.loc.length === 0) {
        //   return this.toast.fail('请选择地区')
        // }
        item.readOnly = !item.readOnly
      }
      this.clipInterface(item, apiVideo.updateClip)
    },
    // 生成剪辑片段
    onSaveOneClip: Fn.Debounce(async function(multi, time = {}) {
      const that = this
      if (!that.validate()) {
        return
      }
      let timeObj = {}
      if (multi) {
        timeObj = {
          parts: JSON.stringify(this.vtimes.map(item => ({ start: item.s, end: item.e, length: item['length'] })))
        }
      } else {
        timeObj = {
          startTime: time.s,
          endTime: time.e,
          length: time['length']
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      const form = {
        ...this.clipModule,
        ...timeObj,
        multi,
        cateOneList: [],
        cateTwoList: [],
        taskId: this.taskId,
        keywords: this.defaultKeywords || ''
      }
      const [err, res] = await this.$await(apiVideo.onlycreate(form))
      if (res) {
        this.getcliplist()
        this.vtimes = []
        this.vStart = this.vEnd = undefined
      }
      loading.close()
    })
  }
}
</script>
<style lang="scss" scoped>
  button{
    margin-left: 0px !important;
    margin-right: 10px;
  }
  .setWidth{
    width:220px;
  }
  //noinspection ALL
  video::-internal-media-controls-download-button {
    display:none !important;
  }
  .view-box {
    /*margin: 5px;*/
    padding: 5px;
  }
  .room {
    padding: 10px;
    /*84 = navbar + tags-view = 50 +34 */
    // height: calc(100vh - 84px);
    height:auto;
    width: 100%;
    position: relative;
    overflow: auto;
    background-color: #f6f7fb;
    .top {
      height: 70px;
    }
    .main {
      width:100%;
      align-items: flex-start;
      .op-area {
        position: relative;
        width: 100%;
        // height: 100%;
        // min-height: calc(100vh);
        min-width: 640px;
        max-width: 60%;
        display: flex;
        flex-direction: column;
        // justify-content: space-between;
        padding:10px;
        .videoStatus{
          position: absolute;
          left: 10px;
          top:10px;
          padding:10px;
          background: rgba(0,0,0,.4);
          color:#fff;
          z-index: 10;
          border-radius: 6px;
        }
        .up {
          position: relative;
          // height: calc(100% - 100px);
          // height:500px;
          // min-height: 480px;
        }
        .down {
          min-height: 100px;
          padding-top:8px;
          display: block;
          .top_operation{
            width:100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding:10px;
            margin-bottom: 10px;
            background-color: #fff;
            .buttons{
              display: inline-flex;
              align-items: center;
              p{
                margin-right: 50px;
                img{
                  width:30px;
                  height:30px;
                }
                &>span{
                  cursor: pointer;
                }
              }

              .quick{
                display: inline-flex;
                align-items: center;
                .el-dropdown-link{
                  margin: 0 10px;
                  transition: .5s;
                  padding:4px;
                }
                .el-dropdown-link:hover{
                  background: #f5f7f8;
                }
                .go,.back{
                  display: inline-flex;
                }
              }
            }
          }

          .inputs{
            width:100%;
            text-align: right;
            .i-select{
              margin:10px 0;
            }
          }
          .timeInfo{
            position: relative;
            width:100%;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            min-height: 100px;
            margin-top: 20px;
            padding:10px;
            box-sizing: border-box;
            background-color: #fff;
            .noData{
              position: absolute;
              top:50%;
              left:50%;
              transform: translate(-50%,-50%);
              color:#909399;
            }
            .timeitem{
              padding:5px 0;
              border-bottom:1px solid#C0C4CC ;
              display: flex;
              align-items: center;
              justify-content: space-between;
              .operation{
                text-align: right;
              }
            }
          }
          button{
            margin:0;
          }
        }
      }
      .right {
        position: relative;
        // height:calc(100vh);
        // max-height: calc(100vh);
        width: 50%;
        min-width: 200px;
        // height: calc(100% - 5px);
        padding:10px 0 10px 10px;
        // padding-right: 10px;
        .empity{
          position: absolute;
          left:50%;
          top:50%;
          transform: translate(-50%,-50%);
          color:#9c9c9c;
        }
        .valid {
          border: solid 0.5px red;
        }
        .text,.speech{
          padding:5px;
          overflow-y:auto;
        }
        ::v-deep .speechitem .el-timeline-item__content{
          color:#F56C6C;
          // filter: grayscale(100%);
        }
        .clipListInfo{
          overflow-y:auto;
          padding:5px;
          .oneclipinfo{
            box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
            padding: 8px;
            margin:10px 5px 0;
            background-color: #fff;
            .moduleitem{
              display: flex;
              align-items: center;
              margin-bottom: 10px;
              .title{
                width:80px;
                text-align: right;
                display: inline-block;
                margin-right: 8px;
              }
              .imgbox{
                display: inline-block;
                width:150px;
                height:90px;
                background:#fff;
                margin-right: 10px;
                img{
                  width:100%;
                  height:100%;
                }
              }
              .info{
                p{
                  margin:6px 0;
                }
              }
              .cate{
                .cate_list{
                  display: flex;
                  flex-wrap: wrap;
                  align-items: center;
                  .list{
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    margin-right: 10px;
                    margin-bottom: 10px;
                    .select{
                      width:150px;
                      margin-right: 10px;
                      margin-bottom: 5px;
                    }
                  }
                }
              }
            }
            ::v-deep .upload{
              .avatar-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                width:50px;
                height:50px;
              }
              .avatar-uploader .el-upload:hover {
                border-color: #409EFF;
              }
              .avatar-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 100%;
                height: 100%;
                line-height: 50px;
                text-align: center;
                position: absolute;
                left:50%;
                top:50%;
                transform: translate(-50%,-50%);
              }
              .el-upload-list__item{
                width:50px;
                height:50px;
                img{
                  width:100%;
                  height:100%;
                }
              }
            }
            .timeInfo{
              .time{
                margin-bottom: 5px;
              }
            }
            .cateinfo{
              display: inherit;
              .cate{
                .cate_title{
                  margin-bottom: 10px;
                }
              }
            }
          }
        }
      }
    }
  }
  .s-border {
    // margin: 2px;
    // padding-right:8px;
    border: solid 1px rgba(1,1,1,0.1);
  }
  .button {
    text-align: center;
    width: auto;
    min-width: 80px;
    height: 50px;
    padding: 10px;
    margin: 0 5px;
  }
  .function {
    text-align: center;
    width: 80px;
    height: 80px;
    padding: 10px 0;
    margin: 5px;
  }
  .setting {
    text-align: center;
    width: 60px;
    height: 60px;
  }
</style>
